#include "qwintspindelegate.h"
// #include "mainwindow.h"

#include <QDoubleSpinBox>
#include <QComboBox>

QWIntSpinDelegate::QWIntSpinDelegate(QObject *parent)
    : QStyledItemDelegate{parent} {}

QWidget *QWIntSpinDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    // 创建代理编辑组件
    Q_UNUSED(option);
    QString s = index.data().toString();
    if(s == "true" || s == "false") {
        QComboBox *editor = new QComboBox(parent);
        editor->setFrame(false); // 无边框
        editor->addItems(QStringList() << "true" << "false");
        return editor;
    } else {
        QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
        editor->setFrame(false); // 无边框
        editor->setSingleStep(10);
        editor->setMinimum(-999999.99);
        editor->setMaximum(999999.99);
        return editor;
    }
}

void QWIntSpinDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
    // 从数据模型中获取数据，显示到代理组件中
    QString s = index.data().toString();
    if(s == "true" || s == "false") {
        QString value = index.model()->data(index, Qt::EditRole).toString();
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        comboBox->setCurrentText(value);
    } else {
        int value = index.model()->data(index, Qt::EditRole).toDouble();
        QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
        spinBox->setValue(value);
    }
}

void QWIntSpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
    // 将代理编辑组件的数据保存到数据模型中
    QString s = index.data().toString();
    if(s == "true" || s == "false") {
        QComboBox *comboBox = static_cast<QComboBox*>(editor);
        QString value = comboBox->currentText();
        model->setData(index, value, Qt::EditRole);
    } else {
        QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
        spinBox->interpretText();
        double value = spinBox->value();
        model->setData(index, value, Qt::EditRole);
    }
}

void QWIntSpinDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    // 设置组件大小
    Q_UNUSED(index);
    editor->setGeometry(option.rect);
}
